package com.hmdp.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisCacheUtil;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;
import static com.hmdp.utils.SystemConstants.SHOP_KEY_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Override
    public Result queryById(Long id) {
        if (id == null) {
            return Result.fail("id不能为空");
        }
        Shop shop = redisCacheUtil.queryWithPassThrough(SHOP_KEY_PREFIX, id, Shop.class, id1 -> getById(id1), 30, TimeUnit.MINUTES);
//        Shop shop = redisCacheUtil.queryWithLogical(SHOP_KEY_PREFIX, id, Shop.class, id1 -> getById(id1), 10, TimeUnit.SECONDS);
        if(shop==null){
            return Result.fail(null);
        }
        return Result.ok(shop);
    }
    @Override
    @Transactional
    public Result uupdateById(Shop shop) {
            //更新数据库
            uupdateById(shop);
            //删除缓存           此顺序可较好的保证多线程下的数据一致性
            stringRedisTemplate.delete(SHOP_KEY_PREFIX+shop.getId());
            return Result.ok();
    }

    @Override
    public Result queryShopsByType(Integer typeId, Integer current, Double x, Double y) {
           if(x==null||y==null){
               // 根据类型分页查询
               Page<Shop> page = query()
                       .eq("type_id", typeId)
                       .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
               // 返回数据
               return Result.ok(page.getRecords());
           }
           int start=(current-1)*DEFAULT_PAGE_SIZE;
           int end=current*DEFAULT_PAGE_SIZE;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                "shop:geo:" + typeId,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> contents = results.getContent();
        //如果开始数据的角标>=所有数据的长度就返回一个空集合
        if(start>=contents.size())return Result.ok(Collections.emptyList());
        List<Long>ids=new ArrayList<>(contents.size());
        Map<String,Distance>distanceMap=new HashMap<>(contents.size());
        contents.stream().skip(start).forEach((data->{
            Distance distance = data.getDistance();
            String idStr = data.getContent().getName();
            ids.add(Long.valueOf(idStr));
            distanceMap.put(idStr,distance);
        }));
        String idsStr = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("order by field(id," + idsStr + ")").list();
        for (Shop shop : shopList) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shopList);
    }

}
